<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import * as echarts from 'echarts'

// 收入数据
const yearlyIncome = ref(0)
const monthlyIncome = ref(0)
const incomeByType = ref([])
const loading = ref(false)

// 图表实例
let pieChart = null

// 初始化饼图
const initPieChart = () => {
  const chartDom = document.getElementById('incomeChart')
  if (!chartDom) return

  pieChart = echarts.init(chartDom)

  const option = {
    title: {
      text: '收入类型分布',
      left: 'center',
      top: 20,
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    series: [
      {
        name: '收入来源',
        type: 'pie',
        radius: ['40%', '70%'], // 环形图
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: ¥{c}\n{d}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        data: [
          { value: 0, name: '广告收入' },
          { value: 0, name: '会员收入' },
          { value: 0, name: '其他收入' }
        ]
      }
    ]
  }

  pieChart.setOption(option)
}

// 获取收入数据
const fetchIncomeData = async () => {
  loading.value = true
  try {
    // 使用Promise.all并发请求数据
    const [yearResult, monthResult, typeResult] = await Promise.all([
      axios.get('/api/income/yearly'),
      axios.get('/api/income/monthly'),
      axios.get('/api/income/by-type')
    ])

    yearlyIncome.value = yearResult.data.data
    monthlyIncome.value = monthResult.data.data
    incomeByType.value = typeResult.data.data

    // 更新饼图数据
    if (pieChart) {
      pieChart.setOption({
        series: [{
          data: incomeByType.value
        }]
      })
    }
  } catch (error) {
    console.error('获取收入数据失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 格式化金额
const formatAmount = (amount) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(amount)
}

// 计算同比增长率
const calculateGrowth = (current, previous) => {
  if (!previous) return 0
  return ((current - previous) / previous * 100).toFixed(2)
}

// 获取趋势图的样式类
const getTrendClass = (value) => {
  return value >= 0 ? 'trend-up' : 'trend-down'
}

onMounted(() => {
  initPieChart()
  fetchIncomeData()

  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    pieChart && pieChart.resize()
  })
})

onUnmounted(() => {
  // 销毁图表实例
  pieChart && pieChart.dispose()
  // 移除事件监听
  window.removeEventListener('resize', () => {
    pieChart && pieChart.resize()
  })
})
</script>

<template>
  <div class="income-statistics">
    <div class="header">
      <h2>收入统计</h2>
      <el-button type="primary" :loading="loading" @click="fetchIncomeData">刷新数据</el-button>
    </div>

    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="12">
        <el-card class="income-card" :loading="loading">
          <template #header>
            <div class="card-header">
              <span>年度总收入</span>
              <el-tag
                :type="yearlyIncome > 1000000 ? 'success' : 'warning'"
                effect="dark"
              >
                同比增长 {{ calculateGrowth(yearlyIncome, yearlyIncome * 0.8) }}%
              </el-tag>
            </div>
          </template>
          <div class="amount">{{ formatAmount(yearlyIncome) }}</div>
          <div class="trend">
            <i :class="['trend-icon', getTrendClass(yearlyIncome - yearlyIncome * 0.8)]"></i>
            较去年{{ yearlyIncome > yearlyIncome * 0.8 ? '增长' : '下降' }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="income-card" :loading="loading">
          <template #header>
            <div class="card-header">
              <span>本月收入</span>
              <el-tag
                :type="monthlyIncome > 100000 ? 'success' : 'warning'"
                effect="dark"
              >
                同比增长 {{ calculateGrowth(monthlyIncome, monthlyIncome * 0.9) }}%
              </el-tag>
            </div>
          </template>
          <div class="amount">{{ formatAmount(monthlyIncome) }}</div>
          <div class="trend">
            <i :class="['trend-icon', getTrendClass(monthlyIncome - monthlyIncome * 0.9)]"></i>
            较上月{{ monthlyIncome > monthlyIncome * 0.9 ? '增长' : '下降' }}
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="chart-card" :loading="loading">
      <div id="incomeChart" class="chart"></div>
    </el-card>
  </div>
</template>

<style scoped>
.income-statistics {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.statistics-cards {
  margin-bottom: 20px;
}

.income-card {
  height: 180px;
  background: linear-gradient(to right bottom, #ffffff, #f8f9fa);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  margin-top: 20px;
  text-align: center;
}

.trend {
  text-align: center;
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}

.trend-icon {
  display: inline-block;
  width: 0;
  height: 0;
  margin-right: 4px;
}

.trend-up {
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-bottom: 6px solid #67C23A;
}

.trend-down {
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 6px solid #F56C6C;
}

.chart-card {
  margin-top: 20px;
}

.chart {
  height: 400px;
  width: 100%;
}

:deep(.el-card__header) {
  padding: 10px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>
